<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品信息管理</title>
<<<<<<< HEAD
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
    <style>
        .input-group{
            display: flex;
        }
        .product-img {
            max-width: 100px;
            max-height: 100px;
        }
        .action-btns {
            white-space: nowrap;
        }
        .table{
            width: 100%;
            border-collapse: collapse;
=======
    llapse;
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
        }
        .table td,th {
            text-align: center;
            vertical-align: middle;
            padding: 8px;
            border: 1px solid #ddd;
        }
        .bottom_{
            display: flex;
            align-items: center;
            justify-content: right;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center">商品信息管理</h2>

    <!-- 搜索和添加区域 -->
    <div class="row mb-3">
        <div class="col-md-6">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索商品名称..." id="searchInput">
                <button class="btn btn-outline-secondary" type="button" id="searchBtn">搜索</button>
<<<<<<< HEAD
=======
                <button class="btn btn-primary" id="addGoodsBtn">添加商品</button>
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
            </div>
        </div>
    </div>

    <!-- 商品表格 -->
    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover">
            <thead class="table-dark table table-striped">
            <tr>
                <th>序号</th>
                <th>商品名称</th>
                <th>价格</th>
                <th>描述</th>
                <th>图片</th>
                <th>状态</th>
                <th>商家ID</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="goodsTableBody">
            <!-- 数据将通过JS动态加载 -->
            </tbody>
        </table>
        <tfoot>
            <td colspan="11" style="text-align: center">

            </td>
        </tfoot>
    </div>

<<<<<<< HEAD


=======
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
    <!-- 分页控件 -->
    <div class="row bottom_">
        <div class="col-md-6">
            <div class="pagination-info" id="paginationInfo">
                显示第 0 至 0 项，共 0 项
            </div>
        </div>
        <div class="col-md-6">
            <nav aria-label="Page navigation" class="float-end" id="pagination">

            </nav>
        </div>
    </div>
</div>

<<<<<<< HEAD

<!-- 删除弹出框 -->
=======
<!-- 删除确认模态框 -->
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
<<<<<<< HEAD
=======
<!--                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>-->
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
            </div>
            <div class="modal-body">
                确定要删除这个商品吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cloce_mode">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确定删除</button>
            </div>
        </div>
    </div>
</div>

<<<<<<< HEAD
<!-- 修改弹出框 -->
<div class="modal fade" id="updateConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑商品信息</h5>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <input type="hidden" id="editId">
                    <div class="mb-3">
                        <label class="form-label">商品名称</label>
                        <input type="text" class="form-control" id="editTitle" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">价格</label>
                        <input type="number" step="0.01" class="form-control" id="editPrice" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="editDescr" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">当前图片</label>
                        <img id="myimg" src="" class="img-thumbnail d-block mb-2" style="max-width: 200px;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">更换图片</label>
                        <input type="file" class="form-control" id="file" onchange="uploadImg()">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">状态</label>
                        <select class="form-select" id="editState">
                            <option value="0">正常销售</option>
                            <option value="1">不可销售</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="close_update">取消</button>
                <button type="button" class="btn btn-primary" id="confirmUpdateBtn">保存修改</button>
            </div>
        </div>
    </div>
</div>

=======
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
<script>
    // 全局变量
    let currentPage = 1;
    const pageSize = 5;
    let totalItems = 0;
    let totalPages = 0;
    let currentGoodsId = null; // 用于存储当前要操作的商品ID

    // 页面加载完成后初始化数据
    $(document).ready(function() {
        initData(currentPage, pageSize);

        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            // currentPage = 1;
            initData(currentPage, pageSize);
        });
<<<<<<< HEAD
=======

        // 添加商品按钮点击事件
        $('#addGoodsBtn').click(function() {
            // 这里可以跳转到添加页面或显示添加模态框
            alert('跳转到添加商品页面');
        });

>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
        // 确认删除按钮点击事件
        $('#confirmDeleteBtn').click(function() {
            if (currentGoodsId) {
                deleteGoods(currentGoodsId);
            }
            $('#deleteConfirmModal').modal('hide');
        });
<<<<<<< HEAD
        // 点击取消
        $('#cloce_mode').click(function() {
            $('#deleteConfirmModal').modal('hide');
        });

        // 绑定更新事件
        $('#confirmUpdateBtn').click(function() {
            updateShoppe()
        });
        // 点击取消
        $('#close_update').click(function() {
            $('#updateConfirmModal').modal('hide');
        });
=======
        $('#cloce_mode').click(function() {
            $('#deleteConfirmModal').modal('hide');
        });
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
    });

    // 初始化数据
    function initData(page, size) {
        const searchKeyword = $('#searchInput').val().trim();
        $.ajax({
            url: 'allGoods',
            type: "GET",
            data: {
                page: page,
                size: size,
                keyword: searchKeyword
            },
            dataType: 'json',
            beforeSend: function() {
                // 添加加载状态
                $('#goodsTableBody').html('<tr><td colspan="8" class="text-center">加载中...</td></tr>');
            },
            success: function(res) {
                if (res.code === 200) {
                    renderTable(res.data);
                    totalItems = res.total;
                    totalPages = Math.ceil(totalItems / pageSize);

                    updatePaginationInfo(page, size, totalItems);
                    renderPagination(page, Math.ceil(totalItems / size));
                } else {
                    alert('获取数据失败: ' + res.msg);
                }
            },
            error: function(xhr, status, error) {
                alert('请求失败: ' + error);
            },
            complete: function() {
                // 移除加载状态
                $('.loading-indicator').remove();
            }
        });
    }

    // 渲染表格数据
    function renderTable(data) {
        const $tbody = $('#goodsTableBody');
        $tbody.empty();

        if (data.length === 0) {
            $tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
            return;
        }

        data.forEach(function(goods) {
            const statusText = goods.state === 0 ? '正常销售' : '不可销售';
            const statusClass = goods.state === 0 ? 'status-0' : 'status-1';

            const row = `
                    <tr>
                        <td>${goods.id}</td>
                        <td>${goods.title}</td>
                        <td>¥${goods.price.toFixed(2)}</td>
                        <td>${goods.descr}</td>
                        <td><img src="${goods.img}" alt="商品图片" class="product-img img-thumbnail"></td>
                        <td class="${statusClass}">${statusText}</td>
                        <td>${goods.mid}</td>
                        <td class="action-btns">
                            <button class="btn btn-sm btn-warning edit-btn" data-id="${goods.id}">编辑</button>
                            <button class="btn btn-sm btn-danger delete-btn" data-id="${goods.id}">删除</button>
                        </td>
                    </tr>
                `;

            $tbody.append(row);
        });

        // 绑定编辑和删除按钮事件
        $('.edit-btn').click(function() {
            const goodsId = $(this).data('id');
            editGoods(goodsId);
        });

        $('.delete-btn').click(function() {
            currentGoodsId = $(this).data('id');
            $('#deleteConfirmModal').modal('show');
        });
    }

    // 更新分页信息
    function updatePaginationInfo(page, size, total) {
        const start = (page - 1) * size + 1;
        let end = page * size;
        if (end > total) end = total;

        $('#paginationInfo').text(` ${start} - ${end} ，共 ${total} `);
    }

    // 渲染分页控件
    function renderPagination(page, totalPages) {
        const $pagination = $('#pagination');
        $pagination.empty();

        let paginationHtml = `
        <ul class="pagination">
            <li class="page-item ${page === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="1">首页</a>
            </li>
            <li class="page-item ${page === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${page - 1}">&laquo;</a>
            </li>`;

        const startPage = Math.max(1, page - 2);
        const endPage = Math.min(totalPages, page + 2);

        for (let i = startPage; i <= endPage; i++) {
            paginationHtml += `
            <li class="page-item ${i === page ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>`;
        }

        paginationHtml += `
            <li class="page-item ${page === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${page + 1}">&raquo;</a>
            </li>
            <li class="page-item ${page === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${totalPages}">尾页</a>
            </li>
        </ul>`;

        $pagination.html(paginationHtml);

        // 统一绑定分页事件
        $pagination.off('click', '.page-link').on('click', '.page-link', function(e) {
            e.preventDefault();
            const newPage = parseInt($(this).data('page'));
            if (!isNaN(newPage) && newPage !== currentPage && newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                initData(currentPage, pageSize);
            }
        });
    }

<<<<<<< HEAD
    // 查询商品信息
    function findShoppe(id){
        $.ajax({
            url: 'goodsDetail',
            type: "GET",
            data: { id: id },
            dataType: 'json',
            success: function(res) {
                if (res.code === 200) {
                    // 填充数据到表单
                    $('#editId').val(res.data.id);
                    $('#editTitle').val(res.data.title);
                    $('#editPrice').val(res.data.price);
                    $('#editDescr').val(res.data.descr);
                    $('#myimg').attr('src', res.data.img);
                    $('#editState').val(res.data.state);
                } else {
                    alert('获取商品信息失败');
                }
            }
        });
    }
    // 更新商品信息
    function updateShoppe(){
        const data = {
            id: $('#editId').val(),
            title: $('#editTitle').val(),
            price: $('#editPrice').val(),
            descr: $('#editDescr').val(),
            state: $('#editState').val(),
            img: document.getElementById('myimg').src
        };
        $.ajax({
            url: 'updateGoods',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',  // 告诉后端这是 JSON
            success: function(res) {
                if (res.code === 200) {
                    $('#updateConfirmModal').modal('hide');
                    initData(currentPage, pageSize); // 刷新列表
                    alert('修改成功');
                } else {
                    alert('修改失败: ' + res.msg);
                }
            }
        });
    }
    // 编辑商品
    function editGoods(id) {
        findShoppe(id)
        // 显示编辑模态框
        $('#updateConfirmModal').modal('show');
=======

    // 编辑商品
    function editGoods(id) {
        // 这里可以跳转到编辑页面或显示编辑模态框
        // alert('跳转到编辑页面，商品ID: ' + id);
        window.location.href = `editgods.html?id=${id}`;
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899

    }

    // 删除商品
    function deleteGoods(id) {
        $.ajax({
            url: 'deleteGoods',
            type: "POST",
            data: { id: id },
            dataType: 'json',
            success: function(res) {
                if (res.code === 200) {
                    alert(res.msg || '操作成功');
                    initData(currentPage, pageSize); // 刷新数据
                } else {
                    alert('操作失败: ' + (res.msg || '未知错误'));
                }
            },
            error: function(xhr) {
                const res = xhr.responseJSON;
                alert('请求失败: ' + (res ? res.msg : xhr.statusText));
            }
        });
    }
<<<<<<< HEAD

    // 上传图片
    function uploadImg () {
        const client = new OSS({
            // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
            region: "oss-cn-hangzhou",
            authorizationV4: true,
            // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
            accessKeyId: "LTAI5tLwyDYHnfqxwEUmmpCg",
            accessKeySecret: "Y7z0wG2dQZqwl12xqcBGjYFhqGeEq5",
            // 从STS服务获取的安全令牌（SecurityToken）。
            // stsToken: "yourSecurityToken",
            // 填写Bucket名称。
            bucket: "dwjm",
        });

        const data = file.files[0];
        putObject(data);

        async function putObject(data) {
            try {
                // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
                // 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
                // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
                const options = {
                    meta: { temp: "demo" },
                    mime: "json",
                    headers: { "Content-Type": "text/plain" },
                };
                let img_data = document.getElementById("file").value
                const result = await client.put(img_data, data, options);
                document.getElementById("myimg").src = result.url
            } catch (e) {
                console.log(e);
            }
        }
    }
=======
>>>>>>> 9734a825be80c2c805cf58c4a2752ba65a920899
</script>
</body>
</html>